package com.tasty.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tasty.constant.MessageConstant;
import com.tasty.dto.UserLoginDTO;
import com.tasty.entity.User;
import com.tasty.exception.LoginFailedException;
import com.tasty.mapper.UserMapper;
import com.tasty.properties.WeChatProperties;
import com.tasty.service.UserService;
import com.tasty.utils.HttpClientUtil;
import com.tasty.utils.WeChatPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {


    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session?";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;


    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */

    public User wxLogin(UserLoginDTO userLoginDTO) {

        String openid = getOpenid(userLoginDTO.getCode());
        //判断当前openid是否为空，如果为空表示登录失败，抛出业务异常
        if (openid == null ){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断当前用户是否为新用户

        /*Map<String, Object> map = new HashMap<>();
        map.put("openid",openid);
        User user = (User) userMapper.selectByMap(map);*/
        User user = userMapper.getByOpenid(openid);

        if (user == null){
            //新用户自动完成注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //返回该用户
        return user;
    }

    /**
     * 调用微信接口服务，获取当前用户openid
     * @param code
     * @return
     */

    private String getOpenid(String code){
        //调用微信接口服务，获取当前用户openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization");

        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
